<script lang="ts" setup>
import { showFailToast, type FieldRule, type FormInstance, showSuccessToast } from 'vant'
import { ref } from 'vue'
import { loginPassword, codeGet, loginPost } from '@/api/user'
import { useUser } from '@/stores'
import { useRouter } from 'vue-router'
import { onBeforeUnmount } from 'vue'
import { useRoute } from 'vue-router'
import { onMounted } from 'vue'
import { useMobileCode } from '@/composable/index'
const store = useUser()
const router = useRouter()
const route = useRoute()
const show = ref(false)
/*
 表单验证
 1：绑定表单元素的值
 2：定义规则
 3：绑定规则
 4：调用表单验证方法
      form组件   validate
*/
const mobile = ref('13211112222')
const password = ref('abc12345') // 8-16位 0-9  a-Z  A-Z
const isAgree = ref(false)
const rules = {
  mobile: [
    { required: true, message: '必填', triegger: 'onChange' },
    { pattern: /^1[3-9]\d{9}$/, message: '请正确输入手机号', trigger: 'onChange' }
  ] as FieldRule[],
  password: [
    { required: true, message: '必填', trigger: 'onChange' },
    { pattern: /^\w{8,16}$/, message: '请输入8-16位密码', trigger: 'onChange' }
  ] as FieldRule[],
  code: [
    { required: true, message: '必填', trigger: 'onChange' },
    { pattern: /^\w{6}$/, message: '请输入6位验证码', trigger: 'onChange' }
  ] as FieldRule[]
}
const form = ref<FormInstance>()
// 确定点击
const submit = async () => {
  await form.value!.validate()
  // 同意了才调用接口
  if (!isAgree.value) {
    // 提示勾选
    return showFailToast('请选勾选协议')
  }
  // 调用登录接口
  const res = isPassword.value
    ? await loginPassword({ mobile: mobile.value, password: password.value })
    : await loginPost({
        mobile: mobile.value,
        code: code.value
      })
  // 存储用户信息
  store.setUserInfo(res.data)
  // 提示
  showSuccessToast('登录成功')
  // 路由跳转
  router.replace((route.query.redirect as string) || '/')
}

// 登陆方式
const isPassword = ref(true)
// 发送验证码
// 1：点击发送验证码，局部表单验证
// 2：定义接口api
// 3:导入api
// 4:局部验证通过调用api
// 5:提示验证码的值
// 短信登录
// 1：定义api
// 2:api参数类型定义
// 3：导入与调用api,获取到数据
// 4：定义返回值数据类型
// 5：完成登录
//  存储用户信息与token
//   提示与跳转
const code = ref('')
// const timeTotal = ref(0) // 倒计时时间值
let timeId = 0
const { cb, timeTotal } = useMobileCode(mobile, 'login')
const sendCode = async () => {
  // 局部表单验证， 验证手机号
  await form.value?.validate('mobile')

  // 获取验证码
  cb()
  // const res = await codeGet({
  //   mobile: mobile.value,
  //   type: 'login'
  // })
  // showSuccessToast(res.data.code)
  // 倒计时功能
  // timeTotal.value = 60
  // clearInterval(timeId)
  // timeId = window.setInterval(() => {
  //   console.log(timeTotal.value)
  //   timeTotal.value--
  //   if (timeTotal.value <= 0) {
  //     clearInterval(timeId)
  //     timeTotal.value = 0
  //   }
  // }, 1000)

  // console.log('验证码', res)
}
// 页面销毁前
onBeforeUnmount(() => {
  clearInterval(timeId)
})
// onMounted(() => {
//   window.QC.Login({
//     btnId: 'qqlogin' //插入按钮的节点id
//   })
// })
const backUrl = encodeURIComponent(import.meta.env.VITE_APP_URL + '/login/callback')
</script>

<template>
  <div class="login-page">
    <cp-nav-bar rightText="注册95" @rightEvent="$router.push('/register')" />
    <!-- 头部 -->
    <div class="login-head">
      <h3>{{ isPassword ? '密码登录' : '短信验证码登录' }}</h3>
      <a href="javascript:;" @click="isPassword = !isPassword">
        <span>{{ !isPassword ? '密码登录' : '短信验证码登录' }}</span>
        <van-icon name="arrow"></van-icon>
      </a>
    </div>
    <!-- 表单 -->
    <van-form autocomplete="off" ref="form">
      <van-field
        :rules="rules.mobile"
        v-model="mobile"
        placeholder="请输入手机号"
        type="tel"
        name="mobile"
      ></van-field>
      <!-- 密码 -->
      <van-field
        v-if="isPassword"
        v-model="password"
        :rules="rules.password"
        placeholder="请输入密码"
        :type="`${show ? 'text' : 'password'}`"
      >
        <template #right-icon>
          <cp-icon @click="show = !show" :name="`login-eye-${show ? 'on' : 'off'}`" />
        </template>
      </van-field>
      <!-- 验证码 -->
      <van-field placeholder="短信验证码" v-else v-model="code" :rules="rules.code">
        <template #button>
          <span class="code" @click="sendCode" v-if="timeTotal === 0">发送验证码</span>
          <span class="code" v-else>{{ timeTotal }}秒后发送验证码</span>
        </template>
      </van-field>
      <div class="cp-cell">
        <van-checkbox v-model="isAgree">
          <span>我已同意</span>
          <a href="javascript:;">用户协议</a>
          <span>及</span>
          <a href="javascript:;">隐私条款</a>
        </van-checkbox>
      </div>
      <div class="cp-cell">
        <van-button block round type="primary" @click="submit">登 录</van-button>
      </div>
      <div class="cp-cell">
        <a href="javascript:;">忘记密码？</a>
      </div>
    </van-form>
    <!-- 底部 -->
    <div class="login-other">
      <van-divider>第三方登录</van-divider>
      <!-- <span id="qqlogin"></span> -->
      <a
        class="icon"
        :href="
          'https://graph.qq.com/oauth2.0/authorize?client_id=102015968&response_type=token&scope=all&redirect_uri=' +
          backUrl
        "
        target="_self"
      >
        <img src="@/assets/qq.svg" alt="" />
      </a>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.login {
  &-page {
    padding-top: 46px;
  }
  &-head {
    display: flex;
    padding: 30px 30px 50px;
    justify-content: space-between;
    align-items: flex-end;
    line-height: 1;
    h3 {
      font-weight: normal;
      font-size: 24px;
    }
    a {
      font-size: 15px;
    }
  }
  &-other {
    margin-top: 60px;
    padding: 0 30px;
    .icon {
      display: flex;
      justify-content: center;
      img {
        width: 36px;
        height: 36px;
        padding: 4px;
      }
    }
  }
}
.van-form {
  padding: 0 14px;
  .cp-cell {
    height: 52px;
    line-height: 24px;
    padding: 14px 16px;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    .van-checkbox {
      a {
        color: var(--cp-primary);
        padding: 0 5px;
      }
    }
  }
  .btn-send {
    color: var(--cp-primary);
    &.active {
      color: rgba(22, 194, 163, 0.5);
    }
  }
}
.code {
  color: var(--van-nav-bar-text-color);
}
</style>
